#' ---
#' title: "Functions: Helper Estimation Functions"
#' author: "Lukas F. Stoetzer"
#' date: "Sep 2020"
#' ---

# Help Wraper function for estimation ===========

  est_mod_time <- function(dat, what="par"){
    
    # Prepare Data
    resp.mat <- dplyr::select(dat,ex,lo,up,pl,pm) %>%
      na.omit() %>%
      as.matrix()/100
    
    # Estimate Model 
    res <- est_eB_beta_manski(resp.mat)
    out <- c(res$par,res$log_lik)
    names(out)[4] <- "log_lik"
    
    # Return 
    return(data.frame(t(out)))
    
  }
  
# Help Wraper function for estimation ===========

est_mod <- function(dat,ret="par",pid=F,...){
  
  
  # Estimate Priors
  if(isFALSE(pid)) {
    prs_mod <- filter(dat, time==0) %>%
      group_by(symmetric) %>%
      do(est_mod_time(.)) 
  } else {
    prs_mod <- filter(dat, time==0) %>%
      ungroup() %>%
      do(est_mod_time(.)) 
  }

  
  # ID
  if(isFALSE(pid)) {
    look_up_id <- dat %>% 
      group_by(id) %>%
      summarise(symmetric = mean(symmetric),
                reverse = mean(reverse))
  } else {
    look_up_id <- dat %>% 
      ungroup() %>%
      select(id) %>% distinct()
  }
  
  # Creat Indvidual Specific ID
  if(isFALSE(pid)){
  prs <- left_join(look_up_id,prs_mod) %>% 
    dplyr::select(alpha,beta) %>% 
    as.matrix()
  } else {
    prs <-  cbind(look_up_id,prs_mod) %>% 
      dplyr::select(alpha,beta) %>% 
      as.matrix()
  }
  
  # Prepare Data
  resp.mat <- filter(dat, time!=0) %>%
    ungroup() %>%
    dplyr::select(ex,lo,up,pl,pm) %>%
    as.matrix()/100
  
  # time
  time <- filter(dat, time!=0) %>% pull(time) %>% as.numeric()
  
  # Polls 
  pollsY <- dat %>% 
    group_by(id) %>%
    dplyr::select(id, time, pollY) %>%
    spread(time,pollY) %>% ungroup() %>%
    dplyr::select(-id) %>% as.matrix()/100
  
  # Estimate Model

    res <- est_dyn_manski_polls(resp.mat,priors=prs,
                                time = time,polls.Y = pollsY, polls.N = 1000)

  
  
  # Priors
  prior_par <- dplyr::select(prs_mod, -sigma, -log_lik) %>%
    gather(par,val) %>% 
    unite(case,c("par")) %>%
    spread(case,val) %>% as.numeric()
  
  # Log_liklihood
  log_lik <-  prs_mod$log_lik + res$log_lik
  out <- c(res$par,log_lik, prior_par[1:2])
  names(out)[4:6] <- c("log_lik", "alpha0","beta0")
 
  # Return 
  if(ret == "all"){
    return(list(res, prs_mod))
  } else {
    return(data.frame(t(out)))      
  }
  
}

## Non-Paramteric Delta estimation =========

calc_delta <- function(de,dp, what="coef"){
  res <- lm(de ~ -1 + dp)
  ifelse(what=="se",sqrt(vcov(res)), coef(res))
}

## Calculate Beleifs from estimates and Polls ====

calc_beliefs <- function(delta, rho, alpha0, beta0, 
                         polls=c(.51,.54,.58), N=1000){
  
  time <- length(polls)
  
  # Define resulting vectors
  alpha <- beta <- NULL
  
  # Prior
  alpha[1] <- alpha0; beta[1] <- beta0
  
  for(t in 1:time){
    
    alpha[t+1] <- delta*alpha[t] + polls[t]*rho*N
    beta[t+1] <- delta*beta[t] + (1-polls[t])*rho*N
    
  }
  
  data.frame("t"= 0:time, alpha, beta) 
}
